package cn.com.bluemoon.daps.sync.core.sync.sql.mysql;

import cn.com.bluemoon.daps.common.toolkit.BmAssetUtils;
import cn.com.bluemoon.daps.sync.core.sync.sql.mysql.datatype.DataTypeHelper;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 11.1 Numeric Data Types
 * 11.2 Date and Time Data Types
 * 11.3 String Data Types
 * 11.4 Spatial Data Types
 * 11.5 The JSON Data Type
 *
 * @author Jarod.Kong
 * @date 2021/6/4 15:36
 */
@Setter
@Getter
@Slf4j
public class MySqlDataType {
    private String name;
    private String length;
    private Integer scale;

    /**
     * 1边界判断
     * 2字段类型解析器
     * 3默认加单引号
     *
     * @param defaultValue 默认值
     * @return 结果
     */
    public Object cast(Object defaultValue) {
        if (defaultValue == null) {
            return null;
        }
        if (name == null) {
            return defaultValue;
        }
        Object defaultVal;
        try {
            defaultVal = DataTypeHelper.castDefaultVal(name, defaultValue);
        } catch (Exception e) {
            defaultVal = "'" + defaultValue + "'";
            log.error("字段类型解析器转换默认值异常，返回默认处理值", e);
        }
        return defaultVal;
    }

    @Override
    public String toString() {
        BmAssetUtils.notNull(name);
        StringBuilder sb = new StringBuilder();
        sb.append(" ").append(name);
        if (length != null) {
            sb.append("(").append(length);
            if (scale != null) {
                sb.append(", ").append(scale);
            }
            sb.append(") ");
        }
        return sb.toString();
    }
}
